﻿/*************************** Copyright *****************************\
 * Copyright 2011 Sendine.com - http://www.sendine.com/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
\*******************************************************************/
using System;
using System.Web;
using System.Text.RegularExpressions;
using Sendine.Web.Route.Cfg;
namespace Sendine.Web.Route
{
    /// <summary>
    /// 路由规则接口
    /// </summary>
    public abstract class RuleValidator
    {
        protected RuleValidator()
        {
            
        }

        public static RuleValidator Create(RouterRule rule)
        {
            RuleValidator validator = null;
            if (string.IsNullOrEmpty(rule.ValidatorName))
            {
                validator = new RegexRuleValidator();
            }
            else
            {
                string asmname, typename;
                SplitTypeName(rule.ValidatorName, out asmname, out typename);
                validator = Activator.CreateInstance(asmname, typename).Unwrap() as RuleValidator;
            }
            validator.Rule = rule;
            return validator;
        }

        private static void SplitTypeName(string fulltypename, out string asmname, out string typename)
        {
            typename = fulltypename.Substring(0, fulltypename.IndexOf(','));
            asmname = fulltypename.Substring(fulltypename.IndexOf(',') + 1);
        }

        protected string lastRequestPath;
        protected string url;
        protected string factoryName;
        protected RouterRule rule;
        protected string calculatedValue;

        /// <summary>
        /// target url
        /// </summary>
        public virtual string Url { get { return url; } set { url = value; } }

        public virtual RouterRule Rule { get { return rule; } set { rule = value; } }

        /// <summary>
        /// http handler name
        /// </summary>
        public virtual string FactoryName
        {
            get { return factoryName; }
        }

        /// <summary>
        /// 匹配Url
        /// </summary>
        /// <param name="requestedPath">Http请求路径</param>
        /// <returns>返回匹配成功或者失败</returns>
        public virtual bool Match(string requestedPath)
        {
            string lookfor = "^" + RouterUtility.ResolveUrl(HttpContext.Current.Request.ApplicationPath, Rule.Regex) + "$";
            lastRequestPath = System.Web.HttpUtility.UrlDecode(requestedPath);
            Regex reg = new Regex(lookfor, RegexOptions.IgnoreCase);
            if (reg.IsMatch(lastRequestPath))
            {
                calculatedValue = reg.Replace(lastRequestPath, Rule.Target);
                foreach (System.Collections.Generic.KeyValuePair<string, string> kv in Rule.Replacement)
                {
                    calculatedValue = calculatedValue.Replace(kv.Key, kv.Value);
                }

                if (!string.IsNullOrEmpty(rule.Trim))
                {
                    calculatedValue = calculatedValue.Trim(rule.Trim.ToCharArray());
                }

                return true;
            }
            else
            {
                calculatedValue = string.Empty;
                return false;
            }
        }

        public virtual IHttpHandlerFactory GetHandlerFactory()
        {
            throw new NotImplementedException();
        }

    }
}
